﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Base64Image
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bt_base2image_Click(object sender, EventArgs e)
        {
            string image = textBox.Text;
            byte[] bits = null;
            try
            {
                bits = Convert.FromBase64String(image);

                using (MemoryStream ms = new MemoryStream(bits, 0, bits.Length))
                {
                    pictureBox.Image = Image.FromStream(ms, true);
                    pictureBox.Width = pictureBox.Image.Width;
                    pictureBox.Height = pictureBox.Image.Height;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void bt_image2base_Click(object sender, EventArgs e)
        {

        }

        private void bt_fromfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Title = "Select Image File";

            fileDialog.Filter = "Text files (*.png)|*.png|All files (*.*)|*.*";

            fileDialog.FilterIndex = 1;

            fileDialog.RestoreDirectory = true;


            String fileName = null;
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {

                fileName = fileDialog.FileName;

                try
                {
                    Bitmap bmp = new Bitmap(fileName);

                    MemoryStream ms = new MemoryStream();
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] arr = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();
                    this.textBox.Text =  Convert.ToBase64String(arr);
                }
                catch (Exception ex)
                {;
                }

            }
            else
            {

            }
        }
    }
}
